package com.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Slf4j
@Order(0)
@WebFilter("/")
public class DeviceFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化操作
        System.out.println("初始化DeviceDetectionFilter");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        //如果是微信公众号的链接，就加上openid
        String openid = httpRequest.getParameter("openid");

        log.warn("经过DeviceFilter这个过滤器");
        log.warn("请求的路径为："+ httpRequest.getRequestURL().toString());
        log.warn(httpRequest.getPathInfo());
        // 获取 User-Agent 来判断设备类型
        String userAgent = httpRequest.getHeader("User-Agent");
        log.info(userAgent);
        boolean isMobile = userAgent != null && (userAgent.contains("iPhone") || userAgent.contains("Android"));

        if (isMobile) {
            // 如果是移动端请求，返回移动端的 index.html
            log.info("是手机访问，返回的转发的路径为："+"index_uniapp.html");
            if(openid!=null){
                httpRequest.getRequestDispatcher("index_uniapp.html?openid="+openid).forward(request, response);
            }else{
                httpRequest.getRequestDispatcher("index_uniapp.html").forward(request, response);
            }

        } else {
            // 否则返回PC端的 index.html
            log.info("是PC访问，返回的转发的路径为："+"index_web.html");
            if(openid!=null){
                httpRequest.getRequestDispatcher("index_web.html?openid="+openid).forward(request, response);
            }else{
                httpRequest.getRequestDispatcher("index_web.html").forward(request, response);
            }

        }
    }

    @Override
    public void destroy() {
        // 销毁操作
    }
}